<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>单页应用初试</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="../../../libs/jquery/3.2.1/jquery.min.js"></script>
    <style>
        #main-view {
            background: #3b76c0;
        }
    </style>
</head>
<script>
    var states;
    var currentState;
    $(document).ready(function () {
        states = registerState();
        currentState = init();

        window.addEventListener('hashchange', onHashChange);
    });

    function onHashChange() {
        var nextState;
        console.log(window.location.hash);
        if (window.location.hash == '') {
            nextState = 'main-view';
        }
        else {
            nextState = window.location.hash.substring(1);
        }
        //判断当前状态是否注册过(是有存在这个状态)
        var validState = checkState(states, nextState);
        //若不存在，则返回当前状态
        if (!validState) {
            console.log("you enter the false validState");
            window.location.hash = "#" + currentState;
            return;
        }
        $('#' + currentState).css("display", "none");
        $('#' + nextState).css("display", "block");
        currentState = nextState;
    }

    function registerState() {
        var states = [];
        $('.pageview').map(function () {
            return states.push($(this)[0].id);
        });
        return states;
    }

    function init() {
        var currentState = window.location.hash.substring(1);
        if (currentState == '') {
            currentState = 'main-view';
        }
        if (currentState != 'main-view') {
            $('#main-view').css('display', 'none');
            $('#' + currentState).css('display', 'block');
        }
        return currentState;
    }

    function checkState(states, nextState) {
        var tof = false;
        states.forEach(element => {
            if (element == nextState) {
                tof = true;
            }
        });
        return tof;
    }
</script>

<body>
    <div><a href="#main-view">首页</a><a href="#list-view">列表页面</a><a href="#detail-view">列表详情页面</a></div>
    <div class="pageview" id='main-view'>
        <h3>首页</h3>
        <div title="-list-view" class='right-arrow'></div>
    </div>
    <div class="pageview" style="background: #58c03b;display: none" id="list-view">
        <h3>列表页面</h3>
        <div class="left-arrow"></div>
        <div title="-detail-view" class="right-arrow"></div>
    </div>
    <div class="pageview" style="background: #c03b25;display: none" id="detail-view">
        <h3>列表详情页面</h3>
        <div class="left-arrow"></div>
    </div>
</body>

</html>